package com.qst.action.PersonalityDimension;

import com.qst.BaseServlet;
import com.qst.ExamException;
import com.qst.RequestUtil;
import com.qst.WebUtil;
import com.qst.entity.PersonalityDimension;
import com.qst.service.AssessmentService;
import com.qst.service.DimensionService;
import com.qst.service.impl.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebServlet("/dimension/save.action")
public class SaveServlet extends BaseServlet {

    private AssessmentService assessmentService = ServiceFactory.getService(AssessmentService.class);
    private DimensionService dimensionService = ServiceFactory.getService(DimensionService.class);

    @Override
    protected void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PersonalityDimension kp = new PersonalityDimension();
        kp.setTitle(RequestUtil.getString(req, "title"));
        kp.setDepict(RequestUtil.getString(req, "depict"));
        kp.setAssessmentId(RequestUtil.getInt(req, "assessmentId"));
        try {
            dimensionService.saveDimension(kp);
            addMessage(req, "性格维度信息已保存到数据库");
            WebUtil.redirect(req, resp, "/dimension/view.action?id=" + kp.getId());
        } catch (ExamException ex) {
            addError(req, ex.getMessage());
            req.setAttribute("dimension", kp);
            req.setAttribute("assessment", assessmentService.findAssessmentById(kp.getAssessmentId()));
            WebUtil.forward(req, resp, "/dimension/create.jsp");
        }
    }
}
